﻿using System.Web.Hosting;
using System.Collections.Generic;
using System;
using System.IO;
using System.Xml.Serialization;
using System.Collections.Specialized;
using System.Web;
using ImageResizer.Util;
using System.Threading;
using ImageResizer;
using ImageResizer.Configuration;
using System.Runtime.Serialization;
using System.Xml;
using sharp_net;
using System.Configuration;
using zkdao.WebImage.ImageServiceReference;

public class PhotoUtils {
    public static string Save(HttpPostedFileBase file, string userKey, NameValueCollection resizeSettings = null) {
        string ID = RandomPassword.GeneratePassword(8);
        string FilePath = PathUtils.SetExtension(ID, PathUtils.GetExtension(file.FileName));
        if (resizeSettings == null || !Config.Current.Pipeline.IsAcceptedImageType(file.FileName)) {
            file.SaveAs(Path.Combine(StoragePath, FilePath));
        } else {
            var job = new ImageJob(file, Path.Combine(StoragePath, ID), new ResizeSettings(resizeSettings));
            job.AddFileExtension = true;
            job.Build();
            FilePath = Path.GetFileName(job.FinalPath);
        }
        using (var imageClient = new ImageServiceClient()) {
            ImageData imgData = new ImageData {
                Path = FilePath
            };
            imgData = imageClient.Creat(imgData, userKey);
            return imgData.ID.ToString();
        }
    }

    public static string UrlWith(string photoPath, string settings) {
        return PathUtils.MergeOverwriteQueryString(ConfigurationManager.AppSettings["PhotoVirtualPath"] + photoPath,
            PathUtils.ParseQueryStringFriendlyAllowSemicolons(settings));
    }

    public static string StoragePath {
        get {
            return HostingEnvironment.MapPath(ConfigurationManager.AppSettings["PhotoStorePath"]);
        }
    }
}